package com.java.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 */
public class R extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public R setData(Object o) {
        put("data", o);
        return this;
    }

    public <T> T getData(String key, TypeReference<T> typeReference) {
        Object o = get(key);
        String s = JSON.toJSONString(o);
        return JSON.parseObject(s, typeReference);
    }

    public <T> T getData(TypeReference<T> typeReference) {
        return getData("data", typeReference);
    }

    public R() {
        put("status", 200);
        put("success", true);
        put("msg", "操作成功");
    }

    public static R ok() {
        return new R();
    }

    public static R ok(Object value) {
        R r = new R();
        r.put("data", value);
        return r;
    }

    public static R error() {
        return error("系统错误,请稍候重试");
    }

    public static R error(String msg) {
        R r = new R();
        r.put("status", 500);
        r.put("success", false);
        r.put("msg", msg);
        return r;
    }

    public static R map(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

}
